package com.zhouzj.task.dubbo.monitor;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Activate(group = {CommonConstants.CONSUMER})
public class TPMonitorFilter implements Filter, Runnable {

    static Map<String, List<MethodInfo>> methodTimes = new ConcurrentHashMap<>();

    {
        Executors.newSingleThreadScheduledExecutor()
                .scheduleWithFixedDelay(this, 5, 5, TimeUnit.SECONDS);
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

        // 获取执行方法名
        Result result = null;
        Long takeTime = 0L;
        try {
            //获取方法执行的起始时间
            Long startTime = System.currentTimeMillis();
            //执行方法
            result = invoker.invoke(invocation);

            if (result.getException() instanceof Exception) {
                throw new Exception(result.getException());
            }
            //计算方法执行的耗时
            takeTime = System.currentTimeMillis() - startTime;
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }

        System.out.println("method=" + invocation.getMethodName() + "消耗的时间:" + takeTime + "毫秒");
        String methodName = invocation.getMethodName();

        List<MethodInfo> methodInfos = methodTimes.get(methodName);

        //方法执行第一次的时候，创建空集合进行存储
        if (methodInfos == null) {
            methodInfos = new ArrayList<>();
            methodTimes.put(methodName, methodInfos);
        }


        methodInfos.removeIf(methodInfo -> methodInfo.getEndTimes() < System.currentTimeMillis() - 60 * 1000);
        //将当前的方法添加到map中指定的记录当前方法执行情况的集合中
        methodInfos.add(new MethodInfo(invocation.getMethodName(), takeTime, System.currentTimeMillis()));

        return result;
    }

    @Override
    public void run() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String dateStr = sdf.format(date);

        /**
         * 线程使用情况
         */
        for (Map.Entry<String, List<MethodInfo>> methodInfos : methodTimes.entrySet()) {
            System.out.println(dateStr + methodInfos.getKey() + "的TP90:" + getTP(methodInfos.getValue(), 0.9) + "毫秒,"
                    + "TP99:" + getTP(methodInfos.getValue(), 0.99) + "毫秒");
        }
    }

    private long getTP(List<MethodInfo> methodInfos, double rate) {
//        // 构建一个临时集合保存 用于满足1一分钟之内的数据
//        List<MethodInfo> sortInfo = new ArrayList<>();
//        // 计算最近一分钟的TP90 和 TP99
//        long endTime = System.currentTimeMillis();
//        long startTime = System.currentTimeMillis() - 60000;
//
//        // 遍历列表集合
//        int length = methodInfos.size();
//        for (int i = 0; i < length; i++) {
//            MethodInfo methodInfo = methodInfos.get(i);
//            if (methodInfo.getEndTimes() >= startTime && methodInfo.getEndTimes() <= endTime) {
//                //将满足条件的方法信息存储到临时集合中
//                sortInfo.add(methodInfo);
//            }
//        }

        //对满足1一分钟之内的数据进行排序
        methodInfos.sort(Comparator.comparing(MethodInfo::getTimes));

        //获取当前排序后集合中的指定百分比数值的位置，此位置存储的数据就是当前计算的tp90/99
        int index = (int) (methodInfos.size() * rate);

        return methodInfos.get(index).getTimes();
    }
}
